﻿using System;
using System.Xml.Linq;

namespace Songhay.Xml
{
    /// <summary>
    /// Static helper members for XML-related routines.
    /// </summary>
    public static partial class XObjectUtility
    {
        /// <summary>
        /// Gets the element or attribute value of the specified element.
        /// </summary>
        /// <param name="currentNode">The current element.</param>
        /// <param name="query">The xpath query.</param>
        public static string GetValue(XNode currentNode, string query)
        {
            return GetValue(currentNode, query, true);
        }

        /// <summary>
        /// Gets the element or attribute value of the specified element.
        /// </summary>
        /// <param name="currentNode">The current node.</param>
        /// <param name="query">The xpath query.</param>
        /// <param name="throwException">if set to <c>true</c> throw exception.</param>
        public static string GetValue(XNode currentNode, string query, bool throwException)
        {
            var node = XObjectUtility.GetXObject(currentNode, query);
            if(node == null)
            {
                if(throwException) throw new ArgumentException("The XPath query returns a null node", "query");
                else return null;
            }

            if(node.NodeType == System.Xml.XmlNodeType.Element)
                return (node as XElement).Value;
            else if(node.NodeType == System.Xml.XmlNodeType.Attribute)
                return (string)XObjectUtility.GetXAttributeValue(currentNode, query, throwException);
            else
                return null;
        }
    }
}
